<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    :title="getTitle" 
    width="600px" 
    @ok="handleSubmit" 
    showFooter
    destroyOnClose
  >
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { inputFormSchemas } from './data';
  import { BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import { saveOrUpdateDataset , getDataset } from '/@/api/infra/dataset';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ColEx } from '/@/components/Form/src/types';
  import {listAllDataSource} from '/@/views/onlineDev/datasource/api';
  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const record = ref<any>({});

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });
  
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    record.value = data.record
    setDrawerProps({ confirmLoading: false, loading: true })

    const resp = await listAllDataSource()
    const options = unref(resp)
    if (options && options.length > 0) {
      updateSchema({
        field: 'datasourceId',
        componentProps: {
          optionFilterProp: "label",
          showSearch: true,
          options,
        },
      });
    }

    try {
      isUpdate.value = !!data?.isUpdate;
      if (unref(isUpdate)) {
        record.value = await getDataset({id: data.record.id}) || {} 
      }

      setFieldsValue({ 
        ...record.value
      })

    } finally {
      setDrawerProps({ loading: false})
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增数据集' : '编辑数据集'));

  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});

      await saveOrUpdateDataset({...values}, unref(isUpdate));
      closeDrawer();
      createMessage.success(`${getTitle.value}成功`)
      emit('success');
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
